
import { 
CreateDictDto, 
UpdateDictDto, 
QueryDictDto, 
DeleteDictDto, 
SelectOneDictDto ,
//SortDictDto
} from '@/dto/dict.dto';
import { AppDataSource } from '@/config/AppDataSource';
import { Dict } from '@/entities/dict.entity';
import { In } from 'typeorm';


class DictService {
    manager = AppDataSource.manager
    private repositor = AppDataSource.getRepository(Dict);
    /**
     * 检验是否已存在唯一
     * @param data  
     * @returns 
     */ 
    async findExcludeId(data: UpdateDictDto) {
        const res = await this.repositor
            .createQueryBuilder('dict')
            .where('dict.id != :id', { id: data.id ||-1 })
            .andWhere('(dict.dictName= :dictName )', data)
            .getOne();
        return res
    }

    /**
     * 创建
     * @param data  
     * @returns 
     */    
    async add(data: CreateDictDto) {        
        // 检查是否已存在
        const findOneName = await this.findExcludeId(data)
        if (findOneName) {
            throw new Error('存在重复');
        }
        // 创建
        const dict = new Dict();
        dict.dictName=data.dictName;
        dict.comment=data.comment;
                   
        const result = await this.repositor.save(dict)
        return result;
    }
    async update(data: UpdateDictDto) {
            // 1. 检查是否存在
        const findOne = await this.repositor.findOneBy({
            id:data.id
        })
        if (!findOne) {
            throw new Error("数据不存在")
        }
        
        // 检查是否已存在
        const findOneName = await this.findExcludeId(data)
        if (findOneName) {
            throw new Error('存在重复'); 
        }
        const dict = new Dict();
        dict.id=data.id!;
        dict.dictName=data.dictName!;
        dict.status=data.status!;
        dict.comment=data.comment!;
        
        return this.repositor.save(dict);
    }

    async selectOne(reqData: SelectOneDictDto) {
        const item = await this.repositor.findOneBy({
            id:reqData.id
        })
        return item;
    }

    async selectList(reqData: QueryDictDto) {
        const { 
            page, 
            pageSize, 
            orderBy,
            fromDate, 
            toDate,
            
            id,
            dictName,
            status,
            createdAt,
            comment,
        } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('dict')
            .select([
                
                'dict.id',
                'dict.dictName',
                'dict.status',
                'dict.createdAt',
                'dict.updatedAt',
                'dict.comment',    
            ]);

        
        if (id) {
            queryBuilder.andWhere('dict.id = :id', { id });
        }
                    
        if (dictName) {
            queryBuilder.andWhere('dict.dictName LIKE :dictName', { name: `%${dictName}%` });
        }                  
                    
        if (status) {
            queryBuilder.andWhere('dict.status = :status', { status });
        }
                    
        if (comment) {
            queryBuilder.andWhere('dict.comment LIKE :comment', { name: `%${comment}%` });
        }                  
                    
        // 添加创建日期范围查询
        if (fromDate && toDate) {
            queryBuilder.andWhere('dict.createdAt BETWEEN :fromDate AND :toDate', {
                fromDate: new Date(fromDate),
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        } else if (fromDate) {
            queryBuilder.andWhere('dict.createdAt >= :fromDate', {
                fromDate: new Date(fromDate)
            });
        } else if (toDate) {
            queryBuilder.andWhere('dict.createdAt <= :toDate', {
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        }
        const [sortBy, sortOrder] = orderBy.split(" ")
        const [dict, total] = await queryBuilder
            .orderBy(`dict.${sortBy}`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
        return {
            list: dict,
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: DeleteDictDto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }
    /**
    async sort(reqData: SortDictDto) {
        const queryRunner = AppDataSource.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();
        try {
            for (const item of reqData.list) {
                await queryRunner.manager.update(
                Dict,
                item.id,
                { sortOrder: item.sortOrder }
                );
            }
            await queryRunner.commitTransaction();
            return { success: true };
        } catch (err) {
            await queryRunner.rollbackTransaction();
        throw err;
        } finally {
            await queryRunner.release();
        } 
    }
    */

}

export default new DictService();    
        
        